<?php

include '../init.php';
//定义您的标识
define("TOKEN", "weixin"); //请将 "weixin" 改为您命名的 TOKEN
$wechatObj = new wechat();
if
 (isset($_GET['echostr'])) {
    $wechatObj->valid();
} else {
    $wechatObj->responseMsg();
}

class wechat {

    public function valid() {
        $echoStr = $_GET["echostr"];
        //有效签名，选项
        if
        ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature() {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if
        ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function responseMsg() {
        //接收数据
        //使用 get 亦或 post 数据，取决于不同环境
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
       // $postStr = '<xml>
       //     <ToUserName>ehlikejf</ToUserName>
       //     <FromUserName>onjq1jq_6MUkhOX_MPhCB_5sEzIg</FromUserName>
       //     <CreateTime>123456789</CreateTime>
       //     <MsgType>event</MsgType>
       //     <Event>CLICK</Event>
       //     <EventKey>MEMBER</EventKey>
       //     </xml>';
        //获取 post 数据
        if (!empty($postStr)) {
            //用 SimpleXML 解析 post 过来的 XML 数据
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $type = trim($postObj->MsgType);
            //判断数据类型
            switch ($type) {
                case "text":
                    $resultStr = $this->receiveText($postObj);
                    break;
                case "image":
                    $resultStr = $this->receiveImg($postObj);
                    break;
                case "event":
                    $resultStr = $this->receiveEvent($postObj);
                    break;
                default:
                    $resultStr = "unknow msg type: " . $type;
                    break;
            }
//             $resultStr =  mb_convert_encoding($resultStr,"UTF-8","GBK");
           // var_dump($resultStr);
            echo $resultStr; //输出结果
        } else {
            echo "";
            exit;
        }
    }

    private function receiveText($object) {
        $funcFlag = 0;
        $keyword = trim($object->Content); //获取消息内容
        $resultStr = "";
        $contentStr = "";
        //返回数据
        //设置回复关键词18
        if ($keyword == "18" || $keyword == " 18" || $keyword == "18 ") {
            $contentStr = '
    <a href="http://www.weixingon.com/wechat/wechatappdev/">微信公众平台应用开发实战</a>
    ';
            $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
            return $resultStr;
        }
        //设置回复关键词21
        if ($keyword == "21" || $keyword == " 21" || $keyword == "21 ") {
            $title = "欢迎进入洞子张";
            $url = "http://kstm.shop5i.com/index.php?go=membership.weixin.api&openid=" . $object->FromUserName;
            $description = "谢谢您的关注！";
            $resultStr = $this->transmitLink($title, $description, $url, $flag = 0);
            return $resultStr;
        }
        //被动自动回复内容
        else {
            $contentStr = '尊敬的粉丝您好！如有问题咨询，请拨打客服电话：

地址：大华三路81号美隆广场2楼
021-61176955

地址：淞兴西路248号1号楼
电话：021-60719778 021-60719779

地址：浦东南路1085号华申大厦3楼美食广场内
电话：021-68388988

地址：共和新路3388号汇客美食广场二楼
电话：021-56889008

地址：金陵东路569号汇通国际广场3楼
电话：021-53861786

地址：七莘路3033号3楼星钻城
电话：021-24288887

地址：国定路333号2号楼2楼洞子张火锅
电话：021-51263508

地址：桂林路400号
电话：021-54668292

地址：长寿路742号
电话：021-62717568
'; //返回消息内容
            $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
            return $resultStr;
        }
    }

    private function receiveImg($object) {
        $mediaid = "";
        $picurl = 'http://kstm.shop5i.com/upload/weixin.png';
        $resultStr = $this->transmitImg($object, $picurl, $mediaid);
        return $resultStr;
    }

    private function receiveEvent($object) {
        $title = "";
        $description = "";
        $url = "";
        switch ($object->Event) {
            case "subscribe":
                //关注後自动推送消息
                $url = "http://kstm.shop5i.com/index.php?go=membership.weixin.api&openid=" . $object->FromUserName;
                $resultStr = "<xml>
                    <ToUserName><![CDATA[".$object->FromUserName."]]></ToUserName>
                    <FromUserName><![CDATA[".$object->ToUserName."]]></FromUserName>
                    <CreateTime>".time()."</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>2</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[点我─加我，享优惠]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/guanzhu1.png]]></PicUrl>
                    <Url><![CDATA[".$url."]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[感谢关注洞子张，点我加粉丝，可以得到成都钟水饺一份，另外可以获得一张价值20元的锅底抵用券]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/guanzhu2.png]]></PicUrl>
                    <Url><![CDATA[".$url."]]></Url>
                    </item>
                    </Articles>
                    </xml>";
                break;
            case "CLICK":
                $resultStr = $this->functionClike($object);
                break;
        }
        return $resultStr;
    }

    private function transmitText($object, $content, $flag = 0) {
        //返回文本消息模板
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        //格式化消息模板
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    private function transmitImg($object, $picurl, $mediaid, $flag = 0) {
        $imgTpl = "<xml>
                 <ToUserName><![CDATA[%s]]></ToUserName>
                 <FromUserName><![CDATA[%s]]></FromUserName>
                 <CreateTime>%s</CreateTime>
                 <MsgType><![CDATA[image]]></MsgType>
                 <PicUrl><![CDATA[%s]]></PicUrl>
                 <MediaId><![CDATA[%s]]></MediaId>
                 <MsgId>%s</MsgId>
                 </xml>";
        //格式化消息模板
        $resultStr = sprintf($imgTpl, $object->FromUserName, $object->ToUserName, time(), $picurl, $mediaid, $flag);
        return $resultStr;
    }

    private function transmitLink($object, $title, $description, $url, $flag = 0) {
        $linkTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[link]]></MsgType>
                <Title><![CDATA[%s]]></Title>
                <Description><![CDATA[%s]]></Description>
                <Url><![CDATA[%s]]></Url>
                <MsgId>%s</MsgId>
                </xml>";
        //格式化消息模板
        $resultStr = sprintf($linkTpl, $object->FromUserName, $object->ToUserName, time(), $title, $description, $url, $flag);
        return $resultStr;
    }

    private function transmitImgText($object, $title, $description, $picurl, $url) {
        $imgtextTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>1</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[%s]]></Title> 
                    <Description><![CDATA[%s]]></Description>
                    <PicUrl><![CDATA[%s]]></PicUrl>
                    <Url><![CDATA[%s]]></Url>
                    </item>
                    </Articles>
                    </xml> ";
        //格式化消息模板
        $resultStr = sprintf($imgtextTpl, $object->FromUserName, $object->ToUserName, time(), $title, $description, $picurl, $url);
        return $resultStr;
    }

    private function functionClike($object) {
        switch ($object->EventKey) {
            case "MEMBER_ADD":
                $resultStr = $this->member_add($object);
                break;
            case "MEMBER_RIGHTS":
                $resultStr = $this->member_rights($object);
                break;
            case "MEMBER":
                $resultStr = $this->member($object);
                break;
            case "SCRATCH_CARD":
                $resultStr = $this->scratch_card($object);
                break;
            case "GOODS":
                $resultStr = $this->goods($object);
                break;
            case "GOODSHOME":
                $resultStr = $this->goodshome($object);
                break;
			case "ADDRESS":
                $resultStr = $this->address($object);
                break;
        }
       // $resultStr = $this->member_add($object);
        return $resultStr;
    }
	
	private function address($object){
        $contentStr = "洞子张老匠火锅（金陵东路店）已上线
地址：金陵东路569号汇通国际广场3楼
电话：021-53861786

洞子张老匠火锅（八佰伴店）已上线
地址：浦东南路1085号华申大厦3楼美食广场内
电话：021-68388988

洞子张老匠火锅（五角场店）待上线
地址：国定路333号2号楼2楼洞子张火锅
电话：021-51263508

洞子张老匠火锅（七宝店）待上线
地址：七莘路3033号3楼星钻城
电话：021-24288887

洞子张老匠火锅（虹梅路店）待上线
地址：虹梅路2971号2楼
电话：021-64655657

洞子张老匠火锅（长寿路店）待上线
地址：长寿路742号
电话：021-62717568

洞子张老匠火锅（淞兴西路店）待上线
地址：淞兴西路248号1号楼
电话：021-60719778 021-60719779

洞子张老匠火锅（大华店）待上线
地址：大华三路81号美隆广场2楼
电话：021-61176955

洞子张老匠火锅（桂林路店）待上线
地址：桂林路400号
电话：021-54668292

洞子张老匠火锅（共和新路店）待上线
地址：共和新路3388号汇客美食广场二楼
电话：021-56889008";
        $resultStr = $this->transmitText($object,$contentStr, $funcFlag=0);
        return $resultStr;
    } 
	
    private function member_add($object) {
        $data = UtilSend::isMember($object->FromUserName);
        if ($data) {
            $resultStr = $this->istMeber($object,$data);
        } else {
            $resultStr = $this->notMeber($object);
        }
        return $resultStr;
    }
    private function member($object){
        $data = UtilSend::isMember($object->FromUserName);
        if ($data) {
            $balance = $point = 0.00;
            $result = UtilApi::getMember($data->phone);
            if($result->code == "A00006") {
                $datacard = $result->data;
                $balance = $datacard->user_balance;
                $point = $datacard->user_point;
            }
            
            $url = "http://kstm.shop5i.com/index.php?go=membership.weixin.api&openid=" . $object->FromUserName;
            $picurl = 'http://kstm.shop5i.com/upload/weixin.png';
            $couponurl = "http://kstm.shop5i.com/index.php?go=membership.coupon.index&openid=" . $object->FromUserName;
            $coupon = UtilSend::getCoupon($data->phone);
            $couponStr = "";
            $j = 3;
            if(!empty($coupon)){
                foreach ($coupon as $key => $value) {
                    $str = $value->batch_name."
面值：".$value->amount."
券码：".$value->coupon_pwd."
有效期：".$value->time."
至".$value->exp_date;
                    $couponStr .="<item>
                    <Title><![CDATA[".$str."]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[]]></PicUrl>
                    <Url><![CDATA[".$couponurl."]]></Url>
                    </item>";
                    $j++;
                }
            }
            $resultStr = "<xml>
                    <ToUserName><![CDATA[".$object->FromUserName."]]></ToUserName>
                    <FromUserName><![CDATA[".$object->ToUserName."]]></FromUserName>
                    <CreateTime>".time()."</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>".$j."</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[出示手机号即可行使权益]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[".$picurl."]]></PicUrl>
                    <Url><![CDATA[".$url."]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[储值余额：".$balance."]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[积分余额：".$point."]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[]]></PicUrl>
                    <Url><![CDATA[".$url."]]></Url>
                    </item>
                    ".$couponStr."
                    </Articles>
                    </xml>";
            return $resultStr;
        } else {
            return $this->notMeber($object);
        }
    }
    private function member_rights($object) {
        $contentStr = '1. 客户到店扫二维码加粉丝，可以得到成都钟水饺一份（当餐可用），另外还可获得一张价值20元的锅底抵用券（限下次消费使用）；
2.客户花9元办理积分会员卡可享有菜品会员价，当餐还可获得哈根达斯冰激凌球一份，消费获得百分之十的积分，一积分抵一元（限下次使用）；
3.储值会员，分三档充600返100，充1000返200，充3000返700，储值会员同样可享会员价，能够得到一份哈根达斯冰激凌球，并且免9元卡工本费 
'; //返回消息内容
        $resultStr = $this->transmitText($object,$contentStr, $funcFlag=0);
        return $resultStr;
    }
    private function scratch_card($object){
        $data = UtilSend::scratch_card($object->FromUserName);
        if ($data) {
            $description = "您有一个张刮刮卡！请进入刮刮卡活动中心刮奖..";
        }else{
            $description = "谢谢您的关注！您目前拥护有0张刮刮卡，详情请进入刮刮卡活动中心..";
        }
        $title = "欢迎进入洞子张";
        $url = "http://kstm.shop5i.com/index.php?go=membership.scratchcard.index&openid=" . $object->FromUserName;
        $picurl = 'http://kstm.shop5i.com/upload/guaguaka.png';
        $resultStr = $this->transmitImgText($object, $title, $description, $picurl, $url);
        return $resultStr;
    }
    private function notMeber($object) {
        $contentStr = "<a href='http://kstm.shop5i.com/index.php?go=membership.weixin.api&openid=" . $object->FromUserName."'>亲,加入会员请点击这里</a>";
        $resultStr = $this->transmitText($object,$contentStr, $funcFlag=0);
        return $resultStr;
    }

    private function istMeber($object,$data) {
        $contentStr = "您已经是粉丝会员了。
手机号：".$data->phone."
开卡日期：".date("Y-m-d",$data->commitTime)."
<a href='http://kstm.shop5i.com/index.php?go=membership.weixin.api&openid=" . $object->FromUserName."'>请查看您的会员卡</a>";
        $resultStr = $this->transmitText($object,$contentStr, $funcFlag=0);
        return $resultStr;
    }

    private function goods($object){
        $resultStr = "<xml>
                    <ToUserName><![CDATA[".$object->FromUserName."]]></ToUserName>
                    <FromUserName><![CDATA[".$object->ToUserName."]]></FromUserName>
                    <CreateTime>".time()."</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>10</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[麻辣鸳鸯锅]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/1.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[九宫格精致牛油全红锅]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/2.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[澳洲牛眼肉]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/3.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[晾杆鸭肠]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/4.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[洞子张绿色毛肚]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/5.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[撒尿牛丸]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/6.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[包心鱼丸]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/7.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[洞子张鲜鹅肠]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/8.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[洞子张军用午餐肉]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/9.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[洞子张鲜黄喉（空运）/四川担担面]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/10.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    </Articles>
                    </xml> ";
        return $resultStr;
    }

    private function goodshome($object){
        $resultStr = "<xml>
                    <ToUserName><![CDATA[".$object->FromUserName."]]></ToUserName>
                    <FromUserName><![CDATA[".$object->ToUserName."]]></FromUserName>
                    <CreateTime>".time()."</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>2</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[品牌介绍]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[http://kstm.shop5i.com/upload/20140918/14.jpg]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    <item>
                    <Title><![CDATA[        有着69年历史传承的洞子张老匠火锅。“洞子”重庆方言，既防空洞的意思。抗战时期为躲避日寇轰炸而建，因洞内冬暖夏凉，解放后市民常聚于此。重庆张氏师傅并以此为契机，将防空洞作为火锅经营场所。张氏师傅潜心研究秘制配方，其火锅口味追求至朴、至纯，麻辣鲜香，代代相传。重庆洞子张第三代传人携传统手艺及厨师团队，搜罗各地美食精华，沿袭传统中华美食料理精髓，融合西方佐餐酱料调配之技艺，与现代的美食理念相结合，为您打造全新的火锅文化]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    </Articles>
                    </xml>";
        return $resultStr;
    }

}

?>